import React, { useState } from 'react';
import { Box, TextField, Accordion, AccordionSummary, AccordionDetails, List, ListItem, ListItemButton, ListItemText, Typography } from '@mui/material';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';

// 依赖类型和modules定义
export interface Module {
  id: string;
  label: string;
  type: string;
  category: string;
}

export const modules: { [key: string]: Module[] } = {
  dataInput: [
    { id: 'csv_reader', label: 'CSV读取器', type: 'csv_reader', category: 'dataInput' },
    { id: 'excel_reader', label: 'Excel读取器', type: 'excel_reader', category: 'dataInput' },
    { id: 'db_reader', label: '数据库读取器', type: 'db_reader', category: 'dataInput' },
  ],
  dataProcessing: [
    { id: 'data_cleaning', label: '数据清洗', type: 'data_cleaning', category: 'dataProcessing' },
    { id: 'data_standardization', label: '数据标准化', type: 'data_standardization', category: 'dataProcessing' },
    { id: 'outlier_detection', label: '异常值检测', type: 'outlier_detection', category: 'dataProcessing' },
    { id: 'one_hot_encoding', label: 'OneHot编码', type: 'one_hot_encoding', category: 'dataProcessing' },
    { id: 'duplicate_removal', label: '重复值处理', type: 'duplicate_removal', category: 'dataProcessing' },
    { id: 'format_conversion', label: '格式转换', type: 'format_conversion', category: 'dataProcessing' },
  ],
  featureSelection: [
    { id: 'feature_selection_filter', label: '过滤法特征选择', type: 'feature_selection_filter', category: 'featureSelection' },
  ],
  machineLearning: [
    { id: 'logistic_regression', label: '逻辑回归', type: 'logistic_regression', category: 'machineLearning' },
    { id: 'random_forest', label: '随机森林', type: 'random_forest', category: 'machineLearning' },
    { id: 'svm', label: 'SVM', type: 'svm', category: 'machineLearning' },
  ],
  visualization: [
    { id: 'structured_view', label: '结构化视图', type: 'structured_view', category: 'visualization' },
    { id: 'model_evaluation', label: '模型评估', type: 'model_evaluation', category: 'visualization' },
  ],
  output: [
    { id: 'csv_writer', label: 'CSV写入器', type: 'csv_writer', category: 'output' },
    { id: 'excel_writer', label: 'Excel写入器', type: 'excel_writer', category: 'output' },
    { id: 'db_writer', label: '数据库写入器', type: 'db_writer', category: 'output' },
  ],
};

const NodePanel: React.FC = () => {
  const [expanded, setExpanded] = useState<string | false>('dataInput');
  const [draggingItem, setDraggingItem] = useState<string | null>(null);
  const [searchTerm, setSearchTerm] = useState('');

  const handleChange = (panel: string) => (event: React.SyntheticEvent, isExpanded: boolean) => {
    setExpanded(isExpanded ? panel : false);
  };

  // 过滤搜索结果
  const filterItems = (items: Module[]) => {
    if (!searchTerm) return items;
    return items.filter(item =>
      item.label.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.type.toLowerCase().includes(searchTerm.toLowerCase())
    );
  };

  // 渲染分类标题
  const getCategoryTitle = (category: string) => {
    const titles: Record<string, string> = {
      'dataInput': '📥 数据输入',
      'dataProcessing': '🔄 数据处理',
      'featureSelection': '🔍 特征选择',
      'machineLearning': '🧠 机器学习',
      'visualization': '📈 数据可视化',
      'output': '📤 数据输出',
    };
    return titles[category] || category;
  };

  // 渲染节点项目
  const renderModuleItem = (item: Module) => (
    <ListItem
      key={item.id}
      disablePadding
      sx={{
        opacity: draggingItem === item.id ? 0.5 : 1,
        transition: 'opacity 0.2s',
        mb: 0.5,
      }}
    >
      <ListItemButton
        draggable
        onDragStart={event => {
          setDraggingItem(item.id);
          event.dataTransfer.setData('application/reactflow', item.type);
          event.dataTransfer.setData('label', item.label);
          event.dataTransfer.effectAllowed = 'move';
        }}
        onDragEnd={() => {
          setDraggingItem(null);
        }}
        sx={{
          borderRadius: '8px',
          border: '1px solid #e0e0e0',
          '&:hover': {
            backgroundColor: 'rgba(25, 118, 210, 0.08)',
            transform: 'translateY(-2px)',
            boxShadow: '0 4px 8px rgba(0,0,0,0.05)',
          },
          transition: 'all 0.2s ease',
          py: 1,
        }}
      >
        <ListItemText
          primary={item.label}
          sx={{
            '& .MuiListItemText-primary': {
              fontSize: '0.9rem',
              fontWeight: 500,
            },
          }}
        />
      </ListItemButton>
    </ListItem>
  );

  return (
    <Box
      sx={{
        width: 280,
        height: '100%',
        borderRight: 1,
        borderColor: 'divider',
        overflow: 'auto',
        display: 'flex',
        flexDirection: 'column',
        backgroundColor: '#fcfcfc',
      }}
    >
      {/* 搜索框 */}
      <Box sx={{ p: 2, pb: 1, borderBottom: '1px solid #f0f0f0' }}>
        <TextField
          fullWidth
          size="small"
          placeholder="搜索组件..."
          value={searchTerm}
          onChange={e => setSearchTerm(e.target.value)}
          variant="outlined"
          InputProps={{
            startAdornment: (
              <Box component="span" sx={{ color: 'text.secondary', mr: 1 }}>
                🔍
              </Box>
            ),
          }}
          sx={{
            '& .MuiOutlinedInput-root': {
              borderRadius: '8px',
            },
          }}
        />
      </Box>
      <Box sx={{ flexGrow: 1, overflow: 'auto', p: 1 }}>
        {Object.entries(modules).map(([category, items]) => {
          const filteredItems = filterItems(items);
          if (searchTerm && filteredItems.length === 0) return null;
          return (
            <Accordion
              key={category}
              expanded={searchTerm ? true : expanded === category}
              onChange={handleChange(category)}
              sx={{
                mb: 1,
                boxShadow: 'none',
                '&:before': {
                  display: 'none',
                },
                backgroundColor: 'transparent',
              }}
            >
              <AccordionSummary
                expandIcon={<ExpandMoreIcon />}
                sx={{
                  minHeight: '48px',
                  borderRadius: '8px',
                  '&:hover': {
                    backgroundColor: 'rgba(0, 0, 0, 0.04)',
                  },
                }}
              >
                <Typography sx={{ fontWeight: 600 }}>{getCategoryTitle(category)}</Typography>
              </AccordionSummary>
              <AccordionDetails sx={{ p: 1 }}>
                <List sx={{ p: 0 }}>{filteredItems.map(renderModuleItem)}</List>
              </AccordionDetails>
            </Accordion>
          );
        })}
      </Box>
      {/* 底部提示 */}
      <Box
        sx={{
          p: 2,
          borderTop: '1px solid #f0f0f0',
          fontSize: '0.75rem',
          color: 'text.secondary',
          textAlign: 'center',
        }}
      >
        拖拽组件到右侧画布构建工作流
      </Box>
    </Box>
  );
};

export default NodePanel; 